<?php

namespace app\api\controller;
use app\BaseController;
use app\model\User as U;
use EasyWeChat\MiniApp\Application;
use app\JWT;
class Login extends BaseController
{

    public function mini(){
        $config = [
            'app_id' => 'wxa2048fc4f7e58119',
            'secret' => '825d7b81775b40a53587544a23b2e951',
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http' => [
                'throw'  => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                'retry' => true, // 使用默认重试配置
            ],
        ];
        $app = new Application($config);
        $session = $app->getUtils()->codeToSession(input('code'));
        // $session = [
        //     'errcode' => 0,
        //     'openid' => 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M',
        //     'unionid' => 'o6_bmasdasdsad6_2sgVt7hMZOPfL',
        //     'session_key' => 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M',
        // ];
        if($session['errcode'] == 0){
            $user = (new U())->where('openid',$session['openid'])->find();
            if(!$user){
                $user = (new U())->create([
                    'openid' => $session['openid'],
                    "unionid" => $session['unionid'],
                    "register_time" => time(),
                    "create_time" => time(),
                ]);
            }
            // 测试JWT生成
            $payload = [
                'user_id' => $user['id'],
                'username' => $user['nickname'],
                'exp' => time() + 3600  // 过期时间1小时
            ];
            $token = JWT::generateJWT($payload);
            return $this->returnApi([
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'name' => $user['name'],
                    'avatar' => $user['avatar'],
                ],
            ],0,'登录成功');
        }else{  // 登录失败 
            return $this->returnApi([],1,'登录失败');
        }
    }

}